package com.laiketui.app.services.dubbo;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.laiketui.app.api.services.CartService;
import com.laiketui.app.common.consts.AppConst;
import com.laiketui.app.controller.CartController;
import com.laiketui.common.api.*;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.PriceUtils;
import com.laiketui.common.utils.tool.base.PathUtil;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.GoodsDataUtils;
import com.laiketui.common.utils.tool.file.EasyPoiExcelUtil;
import com.laiketui.common.utils.tool.jwt.JwtUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.SerializePhpUtils;
import com.laiketui.domain.Page;
import com.laiketui.domain.config.ConfiGureModel;
import com.laiketui.domain.config.ProductConfigModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.mch.CartModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.product.ProductClassModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.Tool.ExcelParamVo;
import com.laiketui.domain.vo.cart.AddCartVo;
import com.laiketui.root.annotation.DubboApiMethod;
import com.laiketui.root.license.Md5Util;
import org.apache.commons.collections.MapUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * 购物车实现
 *
 * @author Trick
 * @date 2020/10/20 9:55
 */
@DubboService(version = "1.0.0", interfaceClass = CartService.class)
public class CartDubboServiceImpl implements CartService {

    private final Logger logger = LoggerFactory.getLogger(CartController.class);

    @Autowired
    ProductConfigModelMapper productConfigModelMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    UserGradeModelMapper userGradeModelMapper;

    @Autowired
    CartModelMapper cartModelMapper;

    @Autowired
    PubliceService publicService;

    @Autowired
    ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    MchModelMapper mchModelMapper;

    @Autowired
    ProductListModelMapper productListModelMapper;

    @Autowired
    CommentsModelMapper commentsModelMapper;

    @Autowired
    CommentsImgModelMapper commentsImgModelMapper;

    @Autowired
    ReplyCommentsModelMapper replyCommentsModelMapper;

    @Autowired
    private PublicMemberService publicMemberService;

    @Autowired
    private PublicGoodsService publicGoodsService;

    @Autowired
    private Cache<String, Object> caffeineCache;

    @Autowired
    private PublicMchService publicMchService;

    @Autowired
    private OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    private ProductClassModelMapper productClassModelMapper;

    @Autowired
    private PublicUserService publicUserService;


    /**
     * 购物车商品推荐列表缓存
     */
    String CART_INDEX_RECOMMONED_PROS_DATA_KEY = "com.laike.app.cartIndex_recommonedpro_";


    @DubboApiMethod(apiKey = "com.laike.products.addCart",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> addCart(AddCartVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        int cartId = 0;
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
            //未登录则看token是否存在,token不存在则生成token 返回前台
            if (StringUtils.isEmpty(vo.getAccessId())) {
                vo.setAccessId(JwtUtils.getToken(publicUserService.getUserLoginLife(vo.getStoreId())));
            }

            //判断商品是否下架
            ProductListModel productListModel = new ProductListModel();
            productListModel.setId(vo.getGoodsId());
            productListModel = productListModelMapper.selectOne(productListModel);
            if (productListModel != null) {
                if (DictionaryConst.GoodsStatus.OFFLINE_GROUNDING.toString().equals(productListModel.getStatus())) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_GSPYXJ, "该商品已下架", "addCart");
                }
                //根据商品规格获取库存信息
                ConfiGureModel confiGureModel = new ConfiGureModel();
                confiGureModel.setId(vo.getAttributeId());
                confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
//                int stockNum = confiGureModel.getNum();
//                //判断库存是否充足
//                if (stockNum >= vo.getNum()) {
                Map<String, Object> parmaMap = new HashMap<>(16);
                //判断购物车是否存在相同商品
                CartModel myCart = new CartModel();
                myCart.setStore_id(vo.getStoreId());
                //如果用户登陆了则用userid
                if (user != null) {
                    myCart.setUser_id(user.getUser_id());
                } else {
                    myCart.setToken(vo.getAccessId());
                }
                myCart.setGoods_id(vo.getGoodsId());
                myCart.setSize_id(vo.getAttributeId() + "");
                myCart = cartModelMapper.selectOne(myCart);
                if (myCart != null) {
                    int needNum = vo.getNum();
                    needNum += myCart.getGoods_num();
//                    if ("addcart".equals(vo.getType())) {
//                        //修改数量
//                        needNum += myCart.getGoods_num();
////                        if (needNum > stockNum) {
////                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KCBZ, "加入购物车数量已超库存数量", "addCart");
////                        }
//                    }
                    parmaMap.put("cart_id", myCart.getId());
                    parmaMap.put("goods_num", needNum);
                    int count = cartModelMapper.updateCartById(parmaMap);
                    if (count < 1) {
                        logger.debug("添加购物车失败-修改购物车 id = " + myCart.getId());
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TJGWCSB, "添加购物车失败", "addCart");
                    }
                    cartId = myCart.getId();
                } else {
                    //添加购物车数据
                    CartModel insertCart = new CartModel();
                    insertCart.setStore_id(vo.getStoreId());
                    insertCart.setGoods_id(vo.getGoodsId());
                    insertCart.setGoods_num(vo.getGoodsId());
                    //如果用户登陆了则用userid
                    if (user != null) {
                        insertCart.setUser_id(user.getUser_id());
                    } else {
                        insertCart.setUser_id("");
                    }
                    insertCart.setToken(vo.getAccessId());
                    insertCart.setGoods_num(vo.getNum());
                    insertCart.setCreate_time(new Date());
                    insertCart.setSize_id(vo.getAttributeId() + "");
                    int count = cartModelMapper.insertSelective(insertCart);
                    if (count < 1) {
                        logger.debug("添加购物车失败 goodsid = " + vo.getGoodsId());
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TJGWCSB, "添加购物车失败", "addCart");
                    }
                }
//            }
//            else {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_KCBZ, "库存不足", "addCart");
//            }
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在", "addCart");
            }
        } catch (
                LaiKeAPIException l) {
            throw l;
        } catch (
                Exception e) {
            logger.error("添加购物车失败", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addCart");
        }
        resultMap.put("cart_id", cartId);
        resultMap.put("type", vo.getType());
        resultMap.put("access_id", vo.getAccessId());
        return resultMap;
    }

    @DubboApiMethod(apiKey = "com.laike.app.cartIndex",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> index(int storeId, String language, String accessId) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        //是否登陆标识
        int loginStatus = 0;
        try {
//            Page pageModel = Page.newBuilder((pageNo - 1) * GloabConst.PageEnum.TERMINAL_DEFAULT_PAGESIZE, GloabConst.PageEnum.TERMINAL_DEFAULT_PAGESIZE, null);

            User user = null;
            String roleDiscount = "1";
            //商品折扣价格
            String discountPrice;
            //计算身份折扣
            roleDiscount = publicMemberService.getMemberDiscountByToken(accessId,storeId);
            //获取用户信息
            user = RedisDataTool.getRedisUserCache(accessId, redisUtil, false);
            if (user != null) {
                loginStatus = 1;

            }

            //商品状态 用于in查询
            List<Integer> goodsStatus = new ArrayList<>();
            //店铺id
//            List<Integer> mchIdList = new ArrayList<>();
            //获取商户产品配置
            ProductConfigModel productConfigModel = new ProductConfigModel();
            productConfigModel.setStore_id(storeId);
            productConfigModel = productConfigModelMapper.selectOne(productConfigModel);
            //已上架
            goodsStatus.add(DictionaryConst.GoodsStatus.NEW_GROUNDING);
            if (productConfigModel != null && productConfigModel.getIs_open() != 0) {
                //已下架
                goodsStatus.add(DictionaryConst.GoodsStatus.OFFLINE_GROUNDING);
            }

            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", storeId);
            //判断是否为游客
            if (user != null) {
                //会员
                parmaMap.put("user_id", user.getUser_id());
            } else {
                //游客
                parmaMap.put("yk_token", accessId);
                parmaMap.put("user_id_not_ull", "user_id_not_ull");
            }
            //上架
//            List<Map<String, Object>> cartList1 = new ArrayList<>();
            //下架、待上架、无库存、已删除
//            List<Map<String, Object>> cartList2 = new ArrayList<>();
            List<Map<String, Object>> resultCartList = new ArrayList<>();
            if (!StringUtils.isEmpty(accessId)) {
                //获取购物车商品数据
                resultCartList = cartModelMapper.getUserShopCartList(parmaMap);
                for (Map<String, Object> map : resultCartList) {
                    int attrId = Integer.parseInt(map.get("size_id").toString());
                    //商品状态
//                    int status = Integer.parseInt(map.get("status").toString());
                    //商品是否回收
//                    int recycle = Integer.parseInt(map.get("recycle").toString());
                    //商品总库存
//                    int stockNumTotal = MapUtils.getIntValue(map, "num");
//                    if (recycle == DictionaryConst.WhetherMaven.WHETHER_OK) {
//                        cartList2.add(map);
//                    } else {
//                        if (DictionaryConst.GoodsStatus.NEW_GROUNDING != status) {
//                            map.put("goodsStatus", 1);
//                            cartList2.add(map);
//                        } else if (stockNumTotal <= 0) {
//                            map.put("goodsStatus", 0);
//                            cartList2.add(map);
//                        } else {
//                            cartList1.add(map);
//                        }
//                    }
                    //产品信息
                    List<Map<String, Object>> skuBeanList = new ArrayList<>();
                    String priceStr = map.get("price") + "";
                    BigDecimal price = new BigDecimal(priceStr);
//                    BigDecimal vipPrice = new BigDecimal(price);
                    //商品id
//                    int pid = Integer.parseInt(map.get("pid") + "");
                    //库存数量
                    int stockNum = Integer.parseInt(map.get("num") + "");
//                    int mchId = Integer.parseInt(map.get("mch_id") + "");
//                    if (!mchIdList.contains(mchId)) {
//                        mchIdList.add(mchId);
//                    }
                    String imgUrl = publicService.getImgPath(map.get("img") + "", storeId);

                    //商品属性
                    StringBuffer attribute = new StringBuffer(map.get("attribute") + "");
                    if (!StringUtils.isEmpty(attribute)) {
                        Map<String, Object> attributeMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(attribute.toString(), Map.class));
                        if (attributeMap != null) {
                            for (String key : attributeMap.keySet()) {
                                String value = attributeMap.get(key) + "";
                                int index = value.indexOf("_LKT_");
                                if (index > 0) {
                                    String attribyteStr = value.substring(0, index);
                                    attribute.append(attribyteStr);
                                }
                            }
                        }
                    }
                    if (stockNum < 1) {
                        stockNum = 0;
                    }
                    //商品配置信息
                    ConfiGureModel confiGure = confiGureModelMapper.selectByPrimaryKey(attrId);
                    //属性处理
                    String cfgAttribute = confiGure.getAttribute();
                    List<Map<String, Object>> attrList = new ArrayList<>();
                    List<Map<String, Object>> attributes = new ArrayList<>();
                    List<String> arrayName = new ArrayList<>();
                    StringBuilder name = new StringBuilder();
                    List<String> parametersList = new ArrayList<>();
                    if (cfgAttribute != null) {
                        Map<String, Object> attributeMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(cfgAttribute, Map.class));
                        if (attributeMap != null) {
                            for (String key : attributeMap.keySet()) {
                                List<Map<String, Object>> attrs = new ArrayList<>();
                                List<String> alls = new ArrayList<>();

                                //是否存在 不存在则添加
                                if (!arrayName.contains(key)) {
                                    Map<String, Object> attrMap = new HashMap<>(16);
                                    arrayName.add(key);
                                    String attribyteKey = key;
                                    String attribyteValue = attributeMap.get(key) + "";
                                    int index = attribyteKey.indexOf("_LKT_");
                                    if (index > 0) {
                                        //属性名称
                                        attribyteKey = attribyteKey.substring(0, attribyteKey.indexOf("_LKT_"));
                                        //属性值
                                        attribyteValue = attribyteValue.substring(0, attribyteValue.indexOf("_LKT_"));
                                    }
//                                    name.append(attribyteValue).append("_");
                                    String parameterStr = attribyteKey + ":" + attribyteValue;
                                    parametersList.add(parameterStr);
                                    name.append(attribyteValue).append(" ");
                                    //属性集合
                                    Map<String, Object> attrArratMap = new HashMap<>(16);
                                    attrArratMap.put("attributeId", Md5Util.MD5endoce(attribyteKey));
                                    attrArratMap.put("attributeValId", Md5Util.MD5endoce(attribyteValue));
                                    attrArratMap.put("enable", false);
                                    attrArratMap.put("select", false);
                                    attrs.add(attrArratMap);
                                    //属性集合
                                    alls.add(attribyteValue + "");

//                                    attrMap.put("attrName", attribyteKey);
//                                    attrMap.put("attrType", "1");
//                                    attrMap.put("id", Md5Util.MD5endoce(attribyteKey));
//                                    attrMap.put("attr", attrs);
//                                    attrMap.put("all", alls);
//                                    attrList.add(attrMap);
//                                    attrMap = new HashMap<>(16);
//                                    attrMap.put("attributeId", Md5Util.MD5endoce(attribyteKey));
//                                    attrMap.put("attributeValId", Md5Util.MD5endoce(attribyteValue));
//                                    attributes.add(attrMap);
                                }
                            }
                        }
                    }
                    //获取产品图片
                    String cimgUrl = publicService.getImgPath(confiGure.getImg(), storeId);
                    //单位
                    String unit = confiGure.getUnit();
                    Map<String, Object> confiGureMap = new HashMap<>(16);
                    // 检查是否以下划线结尾
                    if (name.charAt(name.length() - 1) == '_') {
                        name.deleteCharAt(name.length() - 1); // 删除最后一个字符
                    }
                    //商品分类
                    String goodsClass = MapUtils.getString(map,"product_class");
                    String[] goodsClassList = goodsClass.trim().split("-");
                    String categoryName = "";
                    String areaName = "";
                    //获取分类名称
                    ProductClassModel categoryClass = new ProductClassModel();
                    categoryClass.setCid(Integer.parseInt(goodsClassList[goodsClassList.length-1]));
                    categoryClass = productClassModelMapper.selectOne(categoryClass);
                    ProductClassModel areaClass = new ProductClassModel();
                    areaClass.setCid(Integer.parseInt(goodsClassList[2]));
                    areaClass = productClassModelMapper.selectOne(areaClass);
                    if (categoryClass != null) {
                        categoryName = categoryClass.getPname();
                    }
                    if(areaClass != null){
                        areaName = areaClass.getPname();
                    }
                    confiGureMap.put("name", name);
                    confiGureMap.put("imgurl", cimgUrl);
                    confiGureMap.put("cid", confiGure.getId());
                    confiGureMap.put("price", confiGure.getPrice());
                    confiGureMap.put("count", confiGure.getNum());
                    confiGureMap.put("unit", unit);
                    confiGureMap.put("productCode", confiGure.getProduct_code());
                    confiGureMap.put("marque", confiGure.getMarque());

//                    confiGureMap.put("attributes", attributes);
                    skuBeanList.add(confiGureMap);
                    discountPrice = PriceUtils.mul2(String.valueOf(confiGure.getPrice()),roleDiscount);
                    //折扣 原来价格 * 折扣 / 10 = 优惠价
//                    vipPrice = vipPrice.multiply(gradeRate);

                    map.put("skuName",name);
                    map.put("parameters",parametersList);
                    map.put("id", map.get("id"));
                    map.put("attribute_id", map.get("attribute_id"));
                    map.put("mch_id", map.get("mch_id"));
//                    map.put("pid", map.get("Goods_id"));
                    map.put("price", price);
                    map.put("discountPrice",discountPrice);
                    map.put("productCode",confiGure.getProduct_code());
                    map.put("categoryName",categoryName);
                    map.put("areaName",areaName);
                    map.put("marque",confiGure.getMarque());
                    map.put("material",MapUtils.getString(map,"material"));
                    map.put("capacity",confiGure.getCapacity());
//                    map.put("attribute", mchIdList);
//                    map.put("price", vipPrice);
//                    map.put("num", map.get("Goods_num"));
//                    map.put("productName", map.get("product_title"));
                    map.put("imgurl", imgUrl);
                    map.put("stock", stockNum);
//                    map.put("attrList", attrList);
                    map.put("skuBeanList", skuBeanList);
                    map.put("checked",map.get("checked"));
                }
            }
            //正常上架的商品列表
            resultMap.put("data", resultCartList);
            resultMap.put("login_status", loginStatus);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("进入购物车页面出错", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "index");
        }
        return resultMap;
    }


    @DubboApiMethod(apiKey = "com.laike.app.upCart",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public boolean updateCart(MainVo vo, String goodsJson) throws LaiKeAPIException {
        try {
            JSONArray goodsMap;
            try {
                goodsMap = JSON.parseArray(goodsJson);
            } catch (JSONException j) {
                j.printStackTrace();
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
            if (goodsMap != null && !goodsMap.isEmpty()) {
                for (int i = 0; i < goodsMap.size(); i++) {
                    JSONObject jsonObject = goodsMap.getJSONObject(i);
                    int cartId = Integer.parseInt(jsonObject.get("cart_id") + "");
                    int num = 1;
                    String numObj = jsonObject.get("num") + "";
                    if (com.laiketui.core.diyJavaFunction.StringUtils.isInteger(numObj)) {
                        num = Integer.parseInt(jsonObject.get("num") + "");
                    }
                    if (num < 1) {
                        return false;
                    }
                    CartModel cartModel = new CartModel();
                    cartModel.setId(cartId);
                    if (user != null) {
                        cartModel.setUser_id(user.getUser_id());
                    } else {
                        cartModel.setToken(vo.getAccessId());
                    }
                    cartModel.setStore_id(vo.getStoreId());
                    cartModel = cartModelMapper.selectOne(cartModel);
                    if (cartModel != null) {
                        //属性id
                        int attributeId = Integer.parseInt(cartModel.getSize_id());
                        //根据属性获取库存
//                        ConfiGureModel confiGureModel = new ConfiGureModel();
//                        confiGureModel.setId(attributeId);
//                        confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
//                        int stockNum = confiGureModel.getNum();

                        Map<String, Object> parmaMap = new HashMap<>(16);
                        //如果库存不充足则修改购物车数量为库存总数
                        parmaMap.put("cart_id", cartModel.getId());
                        if (user != null) {
                            parmaMap.put("user_id", user.getUser_id());
                        } else {
                            parmaMap.put("access_id", vo.getAccessId());
                        }
                        parmaMap.put("goods_num", num);
                        int count = cartModelMapper.updateCartById(parmaMap);
                        if (count < 1) {
                            logger.debug("购物车修改失败 购物车id={}", cartModel.getId());
                        } else {
                            return true;
                        }
                    } else {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDGWCSJ, "未找到购物车数据", "upCart");
                    }
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("编辑购物车 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "upCart");
        }
        return false;
    }


    @DubboApiMethod(apiKey = "com.laike.app.delAllCart",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public boolean delAllCart(MainVo vo) throws LaiKeAPIException {
        try {
            if (!StringUtils.isEmpty(vo.getAccessId())) {
                User user;
                Object userObj = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + vo.getAccessId());
                CartModel cartModel = new CartModel();
                cartModel.setStore_id(vo.getStoreId());
                if (userObj != null) {
                    user = JSON.parseObject(userObj.toString(), User.class);
                    if (!StringUtils.isEmpty(user.getUser_id())) {
                        cartModel.setUser_id(user.getUser_id());
                    } else {
                        return false;
                    }
                } else {
                    cartModel.setToken(vo.getAccessId());
                }
                int count = cartModelMapper.delete(cartModel);
                if (count < 1) {
                    logger.debug("购物车清空失败 accessId=" + vo.getAccessId());
                } else {
                    return true;
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("清空购物车出错", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delAllCart");
        }
        return false;
    }

    @DubboApiMethod(apiKey = "com.laike.app.modifyAttribute",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public boolean modifyAttribute(MainVo vo, Integer cartId, Integer attributeId) throws LaiKeAPIException {
        try {
            if (cartId == null || attributeId == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误");
            }
            if (!StringUtils.isEmpty(vo.getAccessId())) {
                Object userObj = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + vo.getAccessId());
                User user = null;
                //获取当前购物车数据
                CartModel currentCart = new CartModel();
                currentCart.setId(cartId);
                currentCart = cartModelMapper.selectOne(currentCart);
                if (currentCart == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDGWCSJ, "未找到购物车数据");
                }
                //获取商品库存的信息
                ConfiGureModel confiGureModel = new ConfiGureModel();
                confiGureModel.setId(attributeId);
                confiGureModel = confiGureModelMapper.selectOne(confiGureModel);
                if (confiGureModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDKCSJ, "未找到库存数据");
                }

                //获取用户购物车当前商品的所有规格数据
                CartModel cartModel = new CartModel();
                cartModel.setStore_id(vo.getStoreId());
                cartModel.setGoods_id(currentCart.getGoods_id());
                if (userObj != null) {
                    user = JSON.parseObject(userObj.toString(), User.class);
                    if (!StringUtils.isEmpty(user.getUser_id())) {
                        cartModel.setUser_id(user.getUser_id());
                    } else {
                        return false;
                    }
                } else {
                    cartModel.setToken(vo.getAccessId());
                }
                boolean isMerge = false;
                //sql参数
                Map<String, Object> parmaMap = new HashMap<>(16);
                List<CartModel> cartModelList = cartModelMapper.select(cartModel);
                for (CartModel cart : cartModelList) {
                    //剔除当前商品
                    if (cart.getId().equals(cartId)) {
                        continue;
                    }

                    //商品如果和原来规格相同则合并
                    if (!cart.getId().equals(cartId) && cart.getGoods_id().equals(currentCart.getGoods_id())) {
                        if (cart.getSize_id().equals(attributeId + "")) {
                            //相同则合并
                            isMerge = true;
                            //合并数量
                            int goodsNum = cart.getGoods_num() + currentCart.getGoods_num();
                            //数量如果超出了总库存数量则强制修改为当前库存数量
                            if (goodsNum > confiGureModel.getNum()) {
                                goodsNum = confiGureModel.getNum();
                            }
                            parmaMap.put("cart_id", currentCart.getId());
                            parmaMap.put("goods_num", goodsNum);
                            parmaMap.put("attributeId", attributeId);
                            cartModelMapper.updateCartById(parmaMap);
                            //删除原来商品
                            cartModel = new CartModel();
                            cartModel.setId(cart.getId());
                            int count = cartModelMapper.delete(cartModel);
                            if (count < 1) {
                                logger.debug("购物车商品合并失败-删除失败 cartid=" + cart.getId());
                            } else {
                                return true;
                            }
                        }
                    }
                }
                if (!isMerge) {
                    //未作修改不动数据库
                    if (!currentCart.getSize_id().equals(attributeId + "")) {
                        //不需要合并则直接修改商品属性
                        parmaMap = new HashMap<>(16);
                        parmaMap.put("cart_id", currentCart.getId());
                        parmaMap.put("attributeId", attributeId);
                        int count = cartModelMapper.updateCartById(parmaMap);
                        if (count < 1) {
                            logger.debug("购物车商品属性修改失败 cartid=" + currentCart.getId());
                        } else {
                            return true;
                        }
                    } else {
                        logger.debug("数据为变化,无需操作 cartid=" + currentCart.getId());
                        return true;
                    }
                }

            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改购物车商品属性出错" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "modifyAttribute");
        }
        return false;
    }


    @DubboApiMethod(apiKey = "com.laike.app.dj_attribute",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public List<Map<String, Object>> djAttribute(MainVo vo, int cartId) throws LaiKeAPIException {
        List<Map<String, Object>> resultList = new ArrayList<>(16);
        try {
            User user = null;
            if (!StringUtils.isEmpty(vo.getAccessId())) {
                if (cartId > 0) {
                    //会员折扣率
                    BigDecimal gradeRate = new BigDecimal("1");
                    if (!StringUtils.isEmpty(vo.getAccessId())) {
                        //获取用户信息
                        user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
                    }
                    //获取购物车数据
                    CartModel cartModel = new CartModel();
                    if (user == null) {
                        cartModel.setToken(vo.getAccessId());
                    } else {
                        cartModel.setUser_id(user.getUser_id());
                    }
                    cartModel.setId(cartId);
                    cartModel = cartModelMapper.selectOne(cartModel);
                    if (cartModel != null) {
                        //获取商品信息
                        ProductListModel productListModel = new ProductListModel();
                        productListModel.setId(cartModel.getGoods_id());
                        productListModel = productListModelMapper.selectOne(productListModel);
                        if (productListModel != null) {
                            //获取商品配置信息
                            ConfiGureModel confiGureModel = new ConfiGureModel();
                            confiGureModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS.toString());
                            confiGureModel.setPid(productListModel.getId());
                            List<ConfiGureModel> confiGureModelList = confiGureModelMapper.select(confiGureModel);
                            //处理图片地址
                            for (ConfiGureModel confiGure : confiGureModelList) {
                                String imgUrl = confiGure.getImg();
                                imgUrl = publicService.getImgPath(imgUrl, vo.getStoreId());
                                confiGure.setImg(imgUrl);
                            }
                            //获取商品规格弹出窗口插件数据
                            Map<String, Object> resultMap = GoodsDataUtils.getGoodsAttributeInfo(confiGureModelList, gradeRate);
                            resultList.add(resultMap);
                        } else {
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDSPSJ, "未找到商品数据", "djAttribute");
                        }
                    } else {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDGWCSJ, "未找到购物车数据", "djAttribute");
                    }
                } else {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误", "djAttribute");
                }
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QDL, "请登录", "djAttribute");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("购物商品属性修改出错", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delAllCart");
        }
        return resultList;
    }


    @Transactional(rollbackFor = Exception.class)
    @DubboApiMethod(apiKey = "com.laike.app.delcart",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public boolean delcart(MainVo vo, String cartIds) throws LaiKeAPIException {
        try {
            if (!StringUtils.isEmpty(vo.getAccessId()) && !StringUtils.isEmpty(cartIds)) {
                String[] cartIdList = cartIds.split(",");
                //获取用户信息
                User user = null;
                Object obj = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + vo.getAccessId());
                if (obj != null) {
                    user = JSON.parseObject(obj.toString(), User.class);
                }
                //循环删除购物车
                CartModel updateCartModel = new CartModel();
                for (String cartId : cartIdList) {
                    updateCartModel.setId(Integer.parseInt(cartId));
                    if (user != null) {
                        updateCartModel.setUser_id(user.getUser_id());
                    } else {
                        updateCartModel.setToken(vo.getAccessId());
                    }
                    int count = cartModelMapper.delete(updateCartModel);
                    if (count < 1) {
                        logger.debug("购物车删除失败 id = " + cartId);
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return false;
                    }
                }
                return true;
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误", "delcart");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除购物车出错" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delcart");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkedCart(MainVo vo, String cartIds) throws LaiKeAPIException {
        try{
            if(StringUtils.isEmpty(vo.getAccessId()) || StringUtils.isEmpty(cartIds)){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW,"参数错误");
            }
            String[] cartArr = cartIds.split(",");
            for(String id : cartArr){
                CartModel cartModel = new CartModel();
                cartModel.setId(Integer.valueOf(id));
                cartModel = cartModelMapper.selectByPrimaryKey(cartModel);
                Integer checked = cartModel.getChecked();
                if(checked == 1){
                    cartModel.setChecked(0);
                }
                if(checked == 0){
                    cartModel.setChecked(1);
                }
//                cartModel.setChecked(!cartModel.isChecked());
                int count = cartModelMapper.updateByPrimaryKeySelective(cartModel);
                if(count < 1){
                    logger.debug("修改购物车状态失败:{}",id);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
            return true;
        }catch (LaiKeAPIException l){
            throw l;
        }catch (Exception e){
            logger.error("修改购物车出错" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delcart");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean checkedAllCart(MainVo vo, String cartIds, Integer checked) throws LaiKeAPIException {
        try{
            if(StringUtils.isEmpty(vo.getAccessId()) || StringUtils.isEmpty(cartIds)){
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW,"参数错误");
            }
            String[] cartArr = cartIds.split(",");
            for(String id : cartArr){
                CartModel cartModel = new CartModel();
                cartModel.setId(Integer.valueOf(id));
                cartModel = cartModelMapper.selectByPrimaryKey(cartModel);
//                checked = cartModel.getChecked();
                if(checked == 1){
                    cartModel.setChecked(1);
                }
                if(checked == 0){
                    cartModel.setChecked(0);
                }
//                cartModel.setChecked(!cartModel.isChecked());
                int count = cartModelMapper.updateByPrimaryKeySelective(cartModel);
                if(count < 1){
                    logger.debug("修改购物车状态失败:{}",id);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return false;
                }
            }
            return true;
        }catch (LaiKeAPIException l){
            throw l;
        }catch (Exception e){
            logger.error("修改购物车出错" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delcart");
        }
    }

    @DubboApiMethod(apiKey = "com.laike.app.goodsExcel",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> goodsExcel(HttpServletResponse response, MainVo vo, Integer supplierOpen,String content) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>();
        try {
            if(vo.getExportType() == 1){
                String roleDiscount = publicMemberService.getMemberDiscountByToken(vo.getAccessId(), vo.getStoreId());
                EasyPoiExcelUtil.goodsExcel(response,roleDiscount ,supplierOpen,content);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.FILE_EXCEL_ERROR, "EXCEL文件导出失败", "excelExport");
        }
        return resultMap;
    }

}

